package com.ztewatch.wearcontacts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.ztewatch.wearcontacts.data.SortItem;
import com.ztewatch.wearcontacts.utils.ConfigLoaderSelectionUtils;
import com.ztewatch.wearcontacts.utils.ContactQuery;
import com.ztewatch.wearcontacts.view.DragGridView;
import com.ztewatch.wearcontacts.view.DragGridView.OnChanageListener;
import com.ztewatch.wearcontacts.view.SortGridViewAdapter;

public class WearContactGroupDetailSortActivity extends Activity {
//	private ScrollGridView base_edit_gridview;
//	private List<HashMap<String, Object>> baseDataList = new ArrayList<HashMap<String, Object>>();
	private List<SortItem> dataSourceList = new ArrayList<SortItem>();
	private DragGridView contact_sort_gridview;
	private SortGridViewAdapter mSortGridViewAdapter;
	private static final int START_PROGRESS = 0x123;
	private static final int STOP_PROGRESS = 0x124;
	private AlertDialog mProgressDialog;
	private Uri groupUri;
	private boolean is_first_come_in = false;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case START_PROGRESS:
				mProgressDialog.show();
				break;
			case STOP_PROGRESS:
				mProgressDialog.dismiss();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_group_detail_sort);
		is_first_come_in = true;
		groupUri = getIntent().getData();
		initContactGridView();
		initProgressDialog();
		if (!mProgressDialog.isShowing()) {
			mHandler.sendEmptyMessage(START_PROGRESS);
		}
//		initBaseGridView();
	}
	
	private void initProgressDialog() {
		AlertDialog.Builder builder = new Builder(this);
		View v = getLayoutInflater().inflate(R.layout.dialog_message_view, null);
		TextView msg = (TextView)v.findViewById(R.id.dialog_message_title);
		msg.setText("init sort...");
		builder.setView(v);
		mProgressDialog = builder.create();
		setDialogBottomShow(mProgressDialog);
	}

	private void setDialogBottomShow(final AlertDialog alertDialog) {
		Window window = alertDialog.getWindow();
		WindowManager.LayoutParams wmlp = window.getAttributes();
		wmlp.gravity = Gravity.BOTTOM;
		window.setAttributes(wmlp);
		alertDialog.setCancelable(false);
	}
	
	private void initContactGridView() {
		contact_sort_gridview = (DragGridView) findViewById(R.id.group_detail_sort_gridview);
		mSortGridViewAdapter = new SortGridViewAdapter(this, dataSourceList);
		contact_sort_gridview.setAdapter(mSortGridViewAdapter);
		contact_sort_gridview.setOnChangeListener(new OnChanageListener() {

			@Override
			public void onChange(int from, int to) {
//				if (from < 0 || to < 0) {
//					return;
//				}
				SortItem temp = dataSourceList.get(from);
				if (from < to) {
					for (int i = from; i < to; i++) {
						Collections.swap(dataSourceList, i, i + 1);
					}
				} else if (from > to) {
					for (int i = from; i > to; i--) {
						Collections.swap(dataSourceList, i, i - 1);
					}
				}
				dataSourceList.set(to, temp);
				mSortGridViewAdapter.notifyDataSetChanged();
			}

			@Override
			public void onDragFinish(int form, int to) {
				saveSortToDatabase(form, to);
			}
		});
	}

	private void saveSortToDatabase(int from, int to) {
		ArrayList<ContentProviderOperation> contact_operations = new ArrayList<ContentProviderOperation>();
		setReflowedPinningOperations(from, to, contact_operations);

		if (!contact_operations.isEmpty()) {
			// update the database here with the new pinned positions
			try {
				getContentResolver().applyBatch(ContactsContract.AUTHORITY,
						contact_operations);
			} catch (RemoteException | OperationApplicationException e) {
			}
		}
	}

	private void setReflowedPinningOperations(int oldPos, int newPinPos,
			ArrayList<ContentProviderOperation> contact_operations) {
		if (oldPos < 0 || newPinPos < 0) {
			return;
		}
		final int lowerBound = Math.min(oldPos, newPinPos);
		final int upperBound = Math.max(oldPos, newPinPos);
		for (int i = lowerBound; i <= upperBound; i++) {
			final SortItem entry = dataSourceList.get(i);

			final int databasePinnedPosition = i + 1;
//			final int databasePinnedPosition = dataSourceList.size() + 1 - i;

			if (entry.getPinned() == databasePinnedPosition)
				continue;
			final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI,
					String.valueOf(entry.getContact_id()));
			final ContentValues values = new ContentValues();
			values.put(Contacts.PINNED, databasePinnedPosition);
			contact_operations.add(ContentProviderOperation.newUpdate(uri)
					.withValues(values).build());
			entry.setPinned(databasePinnedPosition);
		}
	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
			dataSourceList.clear();
			c.moveToPosition(-1);
			while (c.moveToNext()) {
				fillSortListItem(c);
			}
			if (is_first_come_in) {
				is_first_come_in = false;
				if (dataSourceList.size() > 1) {// init sort
					saveSortToDatabase(dataSourceList.size() - 1, 1);
				}
			}
			mSortGridViewAdapter.notifyDataSetChanged();
			if (mProgressDialog.isShowing()) {
				mHandler.sendEmptyMessage(STOP_PROGRESS);
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			CursorLoader cursorLoader = new CursorLoader(
					WearContactGroupDetailSortActivity.this);
			Uri uri = Contacts.CONTENT_URI;
			cursorLoader.setUri(uri);
			cursorLoader.setProjection(ContactQuery.CONTACT_PROJECTION);
			if (groupUri != null) {
				long groupId = ContentUris.parseId(groupUri);
				if (groupId > 0)
					ConfigLoaderSelectionUtils.configGroupSelection(
							cursorLoader, 0, groupId);
			}
			return cursorLoader;
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderCallbacks);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
	}

	private void fillSortListItem(Cursor c) {
		int contact_id_index;
		int name_index;
		int pinned_index;
		int photoId_index;
		contact_id_index = c.getColumnIndex(Contacts._ID);
		name_index = c.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY);
		pinned_index = c.getColumnIndex(Contacts.PINNED);
		photoId_index = c.getColumnIndex(Contacts.PHOTO_ID);
		SortItem sortItem = new SortItem();
		if (contact_id_index != -1) {
			long id = c.getLong(contact_id_index);
			sortItem.setContact_id(id);
		}
		if (name_index != -1) {
			String name = c.getString(name_index);
			sortItem.setName(name);
		}
		if (pinned_index != -1) {
			long pinned = c.getLong(pinned_index);
			sortItem.setPinned(pinned);
		}
		if (photoId_index != -1) {
			long photo_id = c.getLong(photoId_index);
			sortItem.setPhotoId(photo_id);
		}

		dataSourceList.add(sortItem);
	}
}
